if(!console){
  console = {};
  console.log = function(msg){
    }
}

$(document).ajaxStart(function(e, xhr){
  $('#loading').show();
});

$(document).ajaxError(function(e, xhr){
  error(xhr.statusText);
});

$(document).ajaxSuccess(function(e, xhr){
  var msg = xhr.getResponseHeader("X-Message");
  if(msg && msg.length){
    success(msg);
  }
});

$(document).ajaxComplete(function(e, xhr){
  var url = xhr.getResponseHeader("X-Redirect");
  if(url && url.length){
    window.location = url;
  }
  $('#loading').hide();
});

//start modals
$(document).ready(function(){
  $("#error-modal").modal({
    "backdrop"  : "static",
    "keyboard"  : true,
    "show"      : false
  }).css({
    width: '350px'
  }).on('show', function(){
    $(this).css({
      'margin-left': -($(this).width()/2)
    });
  });
  $("#success-modal").modal({
    "backdrop"  : "static",
    "keyboard"  : true,
    "show"      : false
  }).css({
    width: '350px'
  }).on('show', function(){
    $(this).css({
      'margin-left': -($(this).width()/2)
    });
  });
});

function error(text){
  $('#error-modal .modal-body').html(text);
  $('#error-modal').modal('show');
}

function success(text){
  $('#success-modal .modal-body').html(text);
  $('#success-modal').modal('show');
}

//search tag
function tag_search_row_click(id, func){
  $('#' + id + "-tag-search .list-container tr:not(.header-row)").live('click', func);
}

function tag_search_search(id){
  var f = $('#' + id + "-tag-search").data('f');
  f();
}

function tag_search_hide(id){
  $('#' + id + "-tag-search").hide();
}

function tag_search_show(id){
  $('#' + id + "-tag-search").show();
}

$(document).ready(function(){
  
  $('.tag-search').each(function(){
    var tag = $(this);
    if(tag.data('hidden')){
      tag.hide();
    }else{
      tag.show();
    }
    
    var src = tag.data('src');
    var sq = tag.find('.search-query');
    var lc = tag.find('.list-container');
    var rl = tag.find('.result-length');
    var curli = tag.find('.pagination .active');
    var pa = tag.find('.pagination .page');
    var na = tag.find('.pagination .navigation');
    var fa = tag.find('.pagination a[href=#1]');
    var la = tag.find('.pagination a[href=#5]');
    
    var f = function(){
      $.get(appPath + src, {
        query: sq.val(),
        start:rl.val() * (parseInt(curli.find('a').text()) - 1),
        length:rl.val()
      },function(data){
        lc.html(data).show();
      });
    };
    
    tag.data('f', f);
    
    sq.live('keyup', f);
    rl.live('change', f);
    
    pa.live('click', function(){
      var a = $(this);
      if(curli){
        curli.removeClass('active');
      }
      curli = a.parent();
      curli.addClass('active');
      f();
    });
    na.live('click', function(){
      var a = $(this);
      var t = a.attr('href');
      if(t == '#forward'){
        pa.each(function(){
          var i = parseInt($(this).text());
          $(this).text(i + 5);
        });
      }else{
        var f = parseInt(fa.text());
        if(f > 1){
          pa.each(function(){
            var i = parseInt($(this).text());
            $(this).text(i - 5);
          });
          f();
        }
      }
    });
  });
});
//end search tag

function getParameter(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function addParameter(url, parameterName, parameterValue){

  replaceDuplicates = true;

  if(url.indexOf('#') > 0){
    var cl = url.indexOf('#');
    urlhash = url.substring(url.indexOf('#'),url.length);
  } else {
    urlhash = '';
    cl = url.length;
  }

  sourceUrl = url.substring(0,cl);



  var urlParts = sourceUrl.split("?");
  var newQueryString = "";

  if (urlParts.length > 1)
  {
    var parameters = urlParts[1].split("&");
    for (var i=0; (i < parameters.length); i++)
    {
      var parameterParts = parameters[i].split("=");
      if (!(replaceDuplicates && parameterParts[0] == parameterName))
      {
        if (newQueryString == "")
          newQueryString = "?";
        else
          newQueryString += "&";
        newQueryString += parameterParts[0] + "=" + parameterParts[1];
      }
    }
  }
  if (newQueryString == "")
    newQueryString = "?";
  else
    newQueryString += "&";
  newQueryString += parameterName + "=" + parameterValue;

  return urlParts[0] + newQueryString + urlhash;
}

function resetForm(sel) {
  $(sel)[0].reset();
}

function saveForm(formId){
  sessionStorage[window.location.href + '/:form:' + formId] = JSON.stringify($('#' + formId).values());
}

function restoreForm(formId){
  var values = sessionStorage[window.location.href + '/:form:' + formId];
  if(values){
    $('#' + formId).values(JSON.parse(values));
  }
}

localStorage['search_client'] = '/cliniq/clients';
localStorage['create_client'] = '/cliniq/clients/create.jsp';

function redirectForResult(intent){
  sessionStorage['result'] = '';
  sessionStorage['intent'] = intent;
  sessionStorage['callee'] = window.location.href;
  window.location =localStorage[intent];
}

function redirectWithResult(result){
  sessionStorage['intent'] = '';
  sessionStorage['result'] = JSON.stringify(result);
  window.location = sessionStorage['callee'];
}

function request_bind(req, func){
  if(req == sessionStorage['intent']){
    func();
  }
}

function result_bind(func){
  if(sessionStorage['result'] != '' && sessionStorage['result'] != undefined){
    func(JSON.parse(sessionStorage['result']));
  }
}


